package com.laopan.wxpay.request.certificates;

import com.laopan.wxpay.WxConstants;
import com.laopan.wxpay.exception.WxPayException;
import com.laopan.wxpay.utils.PemUtils;

import java.security.cert.X509Certificate;

/**
 * 默认的微信证书信息管理，从配置文件当中读取
 *
 * @author laopan
 * @className DefaultCertificatesManager
 * @date 2021/2/22 17:13
 */

public class DefaultCertificatesManager implements WxCertificatesManager {
    /**
     * 证书存放的根路径，如果不传是默认的classpath下
     */
    private String certificatesRootPath;
    private X509Certificate x509Certificate;

    public DefaultCertificatesManager() {
    }

    public DefaultCertificatesManager setCertificatesRootPath(String certificatesRootPath) {
        this.certificatesRootPath = certificatesRootPath;
        return this;
    }

    @Override
    public X509Certificate getValidCertificate(String mchId) {
        if (mchId == null || mchId.trim().length() == 0) {
            throw new IllegalArgumentException("参数错误,商户id不能为空");
        }
        String certificatesPath = PemUtils.getMerPath(mchId, this.certificatesRootPath, WxConstants.CERTIFICATES_SUFFIX);
        try {
            if (this.x509Certificate == null) {
                this.x509Certificate = PemUtils.loadCertificate(certificatesPath);
            }
            return this.x509Certificate;
        } catch (Exception e) {
            throw new WxPayException(e.getMessage());
        }
    }

    @Override
    public String getUseSerialNo(String mchId) {
        return null;
    }

    @Override
    public X509Certificate refresh(String mchId) {
        return null;
    }
}
